package com.dana.security.handler;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.core.domain.Result;
import com.core.enums.ResultCode;
import com.dana.security.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     *
     请求⽅式不⽀持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request){
        String requestURI = request.getRequestURI();
        log.info("请求地址:'{}',不支持'{}'的请求",requestURI,e.getMethod());
        return Result.fail(ResultCode.ERROR);
    }


    /**
     *
     拦截运⾏时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.info("请求地址:'{}'发生运行时异常",requestURI,e);
        return Result.fail(ResultCode.ERROR);
    }


    /**
     * 参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
        log.error(e.getMessage());
        String message = join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        return Result.fail(ResultCode.FAILED_PARAMS_VALIDATE.getCode(), message);
    }
    private <E> String join(Collection<E> collection, Function<E, String> function, CharSequence delimiter) {
        if (CollUtil.isEmpty(collection)) {
            return StrUtil.EMPTY; // 空集合返回空字符串
        }
        return collection.
                stream()
                .map(function) // 提取每个元素的字段值
                .filter(Objects::nonNull)// 过滤null值
                .collect(Collectors.joining(delimiter)); // 拼接字符串
    }


    /**
     *
     拦截业务出现异常时
     */
    @ExceptionHandler(ServiceException.class)
    public Result<?> handleServiceException(ServiceException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        ResultCode resultCode = e.getResultCode();
        log.info("请求地址:'{}' '{}'发生运行时异常",requestURI,resultCode.getMsg(),e);
        return Result.fail(resultCode.getCode(),resultCode.getMsg());
    }



    /**
     * 拦截所有异常,进行兜底
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.info("请求地址:'{}'发生异常",requestURI,e);
        return Result.fail(ResultCode.ERROR);
    }

}
